package com.djinfo.work.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.djinfo.work.common.bean.AjaxJson;
import com.djinfo.work.common.service.impl.BaseServiceImpl;
import com.djinfo.work.common.util.StringUtil;
import com.djinfo.work.dao.RoleUserDao;
import com.djinfo.work.dao.UserDao;
import com.djinfo.work.dao.impl.UserDaoImpl;
import com.djinfo.work.entity.TbSysRoleUser;
import com.djinfo.work.entity.TbSysRoles;
import com.djinfo.work.entity.TbSysMenu;
import com.djinfo.work.entity.TbSysUsers;
import com.djinfo.work.service.UserService;
import com.djinfo.work.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 实现 登录 首页导航显示
 *
 * @author wxf 实现类
 */
@Service("UserService")
public class UserServiceImpl extends BaseServiceImpl<TbSysUsers,UserDaoImpl> implements UserService {

	/*
	 * 注入
	 */
	@Autowired
	private UserDao userDao=new UserDaoImpl();
	@Autowired
	private RoleUserDao roleUserDao;

	/**
	 * 实现用户登录
	 */
	@Override
	public String getUserID(String username, String password) {
		// TODO Auto-generated method stub
		String isnameorpass = userDao.getUserID(username, password);
		if (isnameorpass == null||"".equals(isnameorpass)) {
			isnameorpass ="";
		}
		return isnameorpass;
	}

	@Override
	public List<TbSysRoles> getUserRoles(String UserId) {
		return userDao.getUserRoles(UserId);
	}

	/**
	 * 登录成功 根据主键id查询用户信息
	 */
	@Override
	public TbSysUsers get(String id) {
		// TODO Auto-generated method stub
		// 参数为空 返回null
		if (id == null) {
			return null;
		}
		TbSysUsers tu=  userDao.get(id);
		/*tu.getQsTestlist().iterator();*/
		if(tu==null){
			return null;
		}
		return tu;

	}

	/**
	 * 左侧导航显示 根据id查询导航菜单信息
	 *
	 * @param id
	 * @return
	 */
	public List<TbSysMenu> authoritiesfindAll(Integer id) {
		return userDao.authoritiesfindAll(id);
	}

	public List<TbSysUsers> getAllUser() {
		return userDao.getAllUser();
	}

	@Override
	public List<TbSysUsers> page(TbSysUsers tbDicRoles, Integer pageNum, Integer pageSize) {
		return userDao.page( tbDicRoles,  pageNum,  pageSize);
	}

	@Override
	public Integer getAllRowCount(TbSysUsers tbSysUsers) {
		return userDao.getAllRowCount(tbSysUsers);
	}

	public void save(TbSysUsers tbSysUsers) {
		this.userDao.save(tbSysUsers);
	}
	public void saveRoleId(String RoleId,String UserId) {
		TbSysRoleUser tbSysRoleUser = new TbSysRoleUser();
		tbSysRoleUser.setRoleId(RoleId);
		tbSysRoleUser.setUserId(UserId);
		this.roleUserDao.save(tbSysRoleUser);
	}

	@Override
	public void updateRoleId(String pkRoleUserId,String roleId, String UserId) {
		TbSysRoleUser tbSysRoleUser =new TbSysRoleUser();
		tbSysRoleUser.setPkRoleUserId(pkRoleUserId);
		tbSysRoleUser.setUserId(UserId);
		tbSysRoleUser.setRoleId(roleId);
		this.roleUserDao.update(tbSysRoleUser);
	}

	@Override
	public void delete(String id) {
		this.userDao.delete(id);
	}


	public Integer getUserID(String userCode) {
		return userDao.getUserID(userCode);
	}

	public TbSysUsers getUserByUserCode(String userCode) {
		return userDao.getUserByUserCode(userCode);
	}

	@Override
	public void update(TbSysUsers tbSysUsers) {
		userDao.update(tbSysUsers);
	}

	@Override
	public void saveRoleUser(TbSysRoleUser tbSysRoleUser) {
		roleUserDao.save(tbSysRoleUser);
	}

	@Override
	public void deleteOneUserRoles(String uid) {
		roleUserDao.deleteUserRoleByUserId(uid);
	}

	@Override
	public ArrayList<TbSysUsers> getUsers(String deptId) {
		return userDao.getUsers(deptId);
	}

	@Override
	public List getUserRoleByUserId(String uid) {
		return roleUserDao.getRoleUserByUserId(uid);
	}

	@Override
	public void deleteUserRoleByUserId(String uid) {
		roleUserDao.deleteUserRoleByUserId(uid);
	}

	@Override
	public AjaxJson getDataList(TbSysUsers tbSysUsers, Integer pagenum, Integer pagesize) {
		AjaxJson ajaxJson=new AjaxJson();
		HashMap map=new HashMap();
		List<TbSysUsers> res = null;
		Integer count = null;
		try {
			res = userDao.page(tbSysUsers,pagenum,pagesize);
			count = userDao.getAllRowCount(tbSysUsers);
			map.put("dataList",res);
			map.put("total",count);
		} catch (Exception e) {
			ajaxJson.setCode(201);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}
		ajaxJson.setResult(map);
		return ajaxJson;
	}

	@Override
	public AjaxJson getRoleUsers(String uid) {
		AjaxJson ajaxJson = new AjaxJson();
		HashMap map=new HashMap();
		List<TbSysRoles> list1= null;
		try {
			list1 = userDao.getUserRoles(uid);
			map.put("roleUserList",list1);
			ajaxJson.setResult(map);
		} catch (Exception e) {
			ajaxJson.setCode(201);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}
		return ajaxJson;
	}

	@Override
	public AjaxJson saveOrUpdate(TbSysUsers tbSysUsers, String[] roles, HttpServletRequest request) {
		AjaxJson ajaxJson = new AjaxJson();
		String userId=(String) request.getSession().getAttribute("userId");
		String nowTime= StringUtil.getNowTime();

			if(tbSysUsers.getPkUserId()==null||"".equals(tbSysUsers.getPkUserId())){
				String md5Password=MD5Utils.GetMD5Code(tbSysUsers.getUserPassword());
				tbSysUsers.setUserPassword(md5Password);
                tbSysUsers.setPkUserId(null);
                tbSysUsers.setCreateTime(nowTime);
                tbSysUsers.setUpdateTime(nowTime);
				tbSysUsers.setCreateUser(userId);
				tbSysUsers.setUpdateUser(userId);
				try {
					userDao.save(tbSysUsers);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(roles!=null) {
                    for (String id : roles) {
                        TbSysRoleUser tbSysRoleUser =new TbSysRoleUser();
                        //String wdUser = userDao.getUserID(tbSysUsers.getUserName(), tbSysUsers.getUserPassword());
                        tbSysRoleUser.setRoleId(id);
                        tbSysRoleUser.setUserId(tbSysUsers.getPkUserId());
                        tbSysRoleUser.setCreateTime(nowTime);
                        tbSysRoleUser.setUpdateTime(nowTime);
                        tbSysRoleUser.setCreateUser(userId);
                        tbSysRoleUser.setUpdateUser(userId);
						try {
							roleUserDao.save(tbSysRoleUser);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
                }
            }else {
                tbSysUsers.setUpdateUser(userId);
                userDao.update(tbSysUsers);
                roleUserDao.deleteUserRoleByRoleId(tbSysUsers.getPkUserId());
                if(roles!=null) {
                    for (String id : roles) {
                        TbSysRoleUser tbSysRoleUser =new TbSysRoleUser();
                        tbSysRoleUser.setRoleId(id);
                        tbSysRoleUser.setUserId(tbSysUsers.getPkUserId());
                        tbSysRoleUser.setCreateUser(userId);
                        tbSysRoleUser.setUpdateUser(userId);
                        tbSysRoleUser.setCreateTime((nowTime));
                        tbSysRoleUser.setUpdateTime(nowTime);
                        roleUserDao.save(tbSysRoleUser);
                    }
                }
            }

		return ajaxJson;
	}

	@Override
	public AjaxJson deleteUser(TbSysUsers tbSysUsers) {
		AjaxJson ajaxJson = new AjaxJson();
		tbSysUsers.setUserName("");
		try {
			roleUserDao.deleteUserRoleByRoleId(tbSysUsers.getPkUserId());
			userDao.delete(tbSysUsers.getPkUserId());
		} catch (Exception e) {
			ajaxJson.setCode(301);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}
		return ajaxJson;
	}

	@Override
	public AjaxJson rePsd(TbSysUsers tbSysUsers, HttpServletRequest request) {
		String userId=(String) request.getSession().getAttribute("userId");
		String nowTime=StringUtil.getNowTime();
		AjaxJson ajaxJson = new AjaxJson();
		tbSysUsers = userDao.get(tbSysUsers.getPkUserId());
		if(tbSysUsers!=null){
			String md5Password=MD5Utils.GetMD5Code("123");
			tbSysUsers.setUserPassword(md5Password);
			tbSysUsers.setUserPassword("123");
			tbSysUsers.setUpdateUser(userId);
			tbSysUsers.setUpdateTime(nowTime);
			try {
				userDao.save(tbSysUsers);
			} catch (Exception e) {
				ajaxJson.setCode(301);
				ajaxJson.setMsg("error");
				e.printStackTrace();
			}
		}
		ajaxJson.setCode(301);
		return ajaxJson;
	}

	@Override
	public AjaxJson addUser(TbSysUsers tbSysUsers) {
		AjaxJson ajaxJson=new AjaxJson();
		String nowTime=StringUtil.getNowTime();
		tbSysUsers.setCreateTime(nowTime);
		tbSysUsers.setUpdateTime(nowTime);
		try {
			userDao.save(tbSysUsers);
		} catch (Exception e) {
			ajaxJson.setCode(301);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}
		return ajaxJson;
	}

	@Override
	public AjaxJson resetPassword(TbSysUsers tbSysUsers) {
		AjaxJson ajaxJson=new AjaxJson();
		String nowTime=StringUtil.getNowTime();
		try {
			tbSysUsers.setUpdateTime(nowTime);
			userDao.update(tbSysUsers);
		} catch (Exception e) {
			ajaxJson.setCode(301);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}
		return ajaxJson;
	}

	@Override
	public AjaxJson checkPhone(String phone) {
		AjaxJson ajaxJson=new AjaxJson();
		String hql=" from TbSysUsers where userName=?";
		List list=userDao.getList(hql,phone);
		if(list.size()==0){
			ajaxJson.setCode(201);
			ajaxJson.setMsg("该号码没有注册过");
		}else{
			ajaxJson.setCode(200);
			ajaxJson.setMsg("该号码注册过");
		}

		return ajaxJson;
	}

	public List getQsList(String userId,String pName){

		String userName = userDao.get(userId).getUserName();
		/*userName = "zhoub";
		userId = "2";*/
		String hql="";
		if(StringUtil.isEmpty(pName)){
			hql="from QsUserQuestionEntity where uId = '"+userId+"' ";
		}else {
			hql="from QsUserQuestionEntity where pName like '"+"%"+pName+"%"+"' and uId = '"+userId+"' ";
		}

		String hql2 = "from QsDictHospital where sales = '"+userName+"' " +
				"or zsm = '"+userName+"' or rsm = '"+userName+"'";
		List list = userDao.getList(hql2);
		if(list!=null&&list.size()>0){
			hql += " or hospital in ( select hospital  "+hql2+" ) order by updateTime ";
		}else {
			hql += " order by updateTime ";
		}
		return userDao.getList(hql);
	}

	@Override
	public void deleteQsList() {
		userDao.deleteQsList();
	}


	@Override
	public TbSysUsers getUserByUsername(String username) {
		TbSysUsers tbSysUsers=new TbSysUsers();
		String hql=" from TbSysUsers where userName=?";
		List list=userDao.getList(hql,username);
		if(list.size()==0){
			return tbSysUsers;
		}else {
			tbSysUsers=(TbSysUsers) list.get(0);
			return tbSysUsers;
		}

	}
}
